﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CsvHelper;
using CsvHelper.Configuration;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ProgressBar;

namespace SourceThicknessDataReview
{
    public partial class Form1 : Form
    {
        List<double> frontThicknessA = new List<double>();
        List<double> frontThicknessB = new List<double>();
        List<double> backThicknessA = new List<double>();
        List<double> backThicknessB = new List<double>();

        //Dictionary<string, double[]> frontThicknessADic = new Dictionary<string, double[]>();
        //Dictionary<string, double[]> frontThicknessBDic = new Dictionary<string, double[]>();
        //Dictionary<string, double[]> backThicknessADic = new Dictionary<string, double[]>();
        //Dictionary<string, double[]> backThicknessBDic = new Dictionary<string, double[]>();
        Dictionary<string, WaveDetail> frontThicknessADic = new Dictionary<string, WaveDetail>();
        Dictionary<string, WaveDetail> frontThicknessBDic = new Dictionary<string, WaveDetail>();
        Dictionary<string, WaveDetail> backThicknessADic = new Dictionary<string, WaveDetail>();
        Dictionary<string, WaveDetail> backThicknessBDic = new Dictionary<string, WaveDetail>();

        Dictionary<string, string> frontADic = new Dictionary<string, string>();
        Dictionary<string, string> backADic = new Dictionary<string, string>();
        Dictionary<string, string> frontBDic = new Dictionary<string, string>();
        Dictionary<string, string> backBDic = new Dictionary<string, string>();

        public Form1()
        {
            InitializeComponent();
            chartDst.Series["Series1"].XValueMember = "wave";
            chartDst.Series["Series1"].YValueMembers = "points";
            chartDst.Series["Series1"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
            chartDst.Series["Series1"].IsValueShownAsLabel = false;
            chartDst.Series["Series2"].XValueMember = "wave";
            chartDst.Series["Series2"].YValueMembers = "points";
            chartDst.Series["Series2"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
            chartDst.Series["Series2"].IsValueShownAsLabel = false;
        }

        private async void btnChoose_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            opf.InitialDirectory = "C:\\Users\\pc-admin\\Desktop\\Data";
            opf.Filter = "excel files|*.xls|*.xlsx|*.csv";
            opf.FilterIndex = 2;
            if (opf.ShowDialog() == DialogResult.OK)
            {
                string filepath = opf.FileName;
                txtPath.Text = filepath;
            }
            else
            {
                txtPath.Text = "";
            }

            string[] content = ReadCsv(txtPath.Text);
            Parse(content);
            lblMax.Text = "";
            lblMin.Text = "";
        }

        private string[] ReadCsv(string filePath)
        {
            string[] content = File.ReadAllLines(filePath);
            return content;
        }

        private async void Parse(string[] details)
        {
            frontThicknessA = new List<double>();
            frontThicknessB = new List<double>();
            backThicknessA = new List<double>();
            backThicknessB = new List<double>();
            foreach (var line in details)
            {
                string[] fields = line.Split(',');
                switch (fields[0])
                {
                    case "1":
                        backThicknessB.Add(Convert.ToDouble(fields[1]));
                        //this.Invoke(new Action(() =>
                        //{
                        //    txtSrcBackB.AppendText(fields[1]);
                        //}));
                        break;
                    case "2":
                        frontThicknessB.Add(Convert.ToDouble(fields[1]));
                        //this.Invoke(new Action(() =>
                        //{
                        //    txtSrcFrontB.AppendText(fields[1]);
                        //}));
                        break;
                    case "3":
                        backThicknessA.Add(Convert.ToDouble(fields[1]));
                        //this.Invoke(new Action(() =>
                        //{
                        //    txtSrcBackA.AppendText(fields[1]);
                        //}));
                        break;
                    case "4":
                        frontThicknessA.Add(Convert.ToDouble(fields[1]));
                        //this.Invoke(new Action(() =>
                        //{
                        //    txtSrcFrontA.AppendText(fields[1]);
                        //}));
                        break;
                }

            }

            var frontA = await ParseDistanceAndThickness(frontThicknessA);
            var backA = await ParseDistanceAndThickness(backThicknessA);
            var frontB = await ParseDistanceAndThickness(frontThicknessB);
            var backB = await ParseDistanceAndThickness(backThicknessB);


            //frontThicknessADic = await CalculateThicknessAlgorithmNew("FCTA", frontA.Item1, frontA.Item2);
            //backThicknessADic = await CalculateThicknessAlgorithmNew("BCTA", backA.Item1, backA.Item2);
            //frontThicknessBDic = await CalculateThicknessAlgorithmNew("FCTB", frontB.Item1, frontB.Item2);
            //backThicknessBDic = await CalculateThicknessAlgorithmNew("BCTB", backB.Item1, backB.Item2);

            frontThicknessADic = await CalculateThicknessAlgorithmUsePulse("FCTA", frontA.Item1, frontA.Item2);
            backThicknessADic = await CalculateThicknessAlgorithmUsePulse("BCTA", backA.Item1, backA.Item2);
            frontThicknessBDic = await CalculateThicknessAlgorithmUsePulse("FCTB", frontB.Item1, frontB.Item2);
            backThicknessBDic = await CalculateThicknessAlgorithmUsePulse("BCTB", backB.Item1, backB.Item2);
        }


        /// <summary>
        /// 解析存放膜厚和膜厚距离
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private async Task<(List<double>, List<double>)> ParseDistanceAndThickness(List<double> list)
        {
            List<double> dis = new List<double>();
            List<double> thick = new List<double>();
            if (list.Any())
            {
                for (int i = 1; i <= list.Count; i++)
                {
                    if (i % 2 == 0)//存放膜厚
                    {
                        thick.Add(list[i - 1]);
                    }
                    else
                    {
                        dis.Add(list[i - 1]);
                    }
                }
                return (dis, thick);
            }
            return (null, null);
        }

        private bool Judge(double value)
        {
            if (value >= 0.5 && value <= 3.6)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 计算膜厚算法 新
        /// </summary>
        /// <param name="detectionType">检测类型</param>
        /// <param name="dis">距离数组</param>
        /// <param name="thick">膜厚数组</param>
        /// <returns></returns>
        private async Task<Dictionary<string, WaveDetail>> CalculateThicknessAlgorithmNew(string detectionType, List<double> disList, List<double> thickList)
        {
            //if (disList.Count > 8000)
            //{
            //    disList.RemoveRange(0, 7999);
            //}
            //if (thickList.Count > 8000)
            //{
            //    thickList.RemoveRange(0, 7999);
            //}
            double temp = 0;//临时变量
            int findValidValueCount = 0;
            int idx = 0;
            List<double> tempList = new List<double>();
            List<double> tempThickList = new List<double>();
            List<double> finalList = new List<double>();
            Dictionary<string, WaveDetail> result = new Dictionary<string, WaveDetail>();
            foreach (var item in disList)
            {
                if (item == -2147.483648)
                {
                    findValidValueCount++;
                    if (findValidValueCount >= 35/*35*/)
                    {
                        if (item != temp)
                        {
                            tempList.Add(item);
                            tempThickList.Add(thickList[idx]);
                            temp = item;
                            findValidValueCount = 0;
                        }
                    }
                }
                else
                {
                    if (item != temp && item != -2147.483648)
                    {
                        tempList.Add(item);
                        tempThickList.Add(thickList[idx]);
                        temp = item;
                        findValidValueCount = 0;
                    }
                }
                idx++;
            }
            int index = tempList.IndexOf(-2147.483648);
            int endIndex = 0;
            DateTime starttime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            double timediff = 0;
            int count = 1;
            while (index != -1)
            {
                index = tempList.IndexOf(-2147.483648);
                if (index != -1)//找到起始位置
                {
                    endIndex = tempList.IndexOf(-2147.483648, index + 1);
                    if (endIndex != -1)//找到结束位置
                    {
                        double totalValue = 0;
                        double thicknessValue = 0;
                        double[] disArray = tempList.GetRange(index + 1, endIndex - index - 1).ToArray();//有效距离数组
                        double[] thickArray = tempThickList.GetRange(index + 1, endIndex - index - 1).ToArray();
                        double[] avgAry = new double[50];
                        avgAry.Initialize();
                        int thickIndex = 0;
                        if (detectionType.Contains("FCT"))
                        {
                            thickIndex = disArray.ToList().FindIndex(f => f == disArray.Max());//找到膜厚下标
                        }
                        else
                        {
                            thickIndex = disArray.ToList().FindIndex(f => f == disArray.Min());//找到膜厚下标
                        }
                        double diffZoneLeft = disArray[0] - disArray[thickIndex];
                        double diffZoneRight = disArray[disArray.Length - 1] - disArray[thickIndex];

                        bool resLeft = Judge(Math.Abs(diffZoneLeft));
                        bool resRight = Judge(Math.Abs(diffZoneRight));
                        bool res = true;
                        if (count == 1 || count == 2)
                        {
                            if (resLeft && resRight)
                            {
                                res = true;
                            }
                            else
                            {
                                res = false;
                            }
                        }
                        if (disArray.Length > 5/*20*/ && res/*resLeft && resRight*/)
                        {
                            for (int i = 0; i < 25; i++)
                            {
                                if (thickIndex + i < thickArray.Length - 1 && thickIndex - i < thickArray.Length - 1 /*&& thickIndex != 0*/ && thickIndex - i >= 0)
                                {
                                    double value = thickArray[thickIndex - i];
                                    if (value != -2147.483648)
                                    {
                                        totalValue += value;
                                        avgAry[i] = value;
                                        if (thickArray[thickIndex + i] != -2147.483648)
                                        {
                                            double valueSum = thickArray[thickIndex + i];
                                            totalValue += valueSum;
                                            avgAry[24 + i] = valueSum;
                                        }
                                    }
                                    else if (thickArray[thickIndex + i] != -2147.483648)
                                    {
                                        double valueSum1 = thickArray[thickIndex + i];
                                        totalValue += valueSum1;
                                        avgAry[24 + i] = valueSum1;
                                    }
                                }
                            }
                            thicknessValue = totalValue / avgAry.Where(f => f != 0).ToArray().Length;//均值计算
                            finalList.Add(thicknessValue);
                            WaveDetail waveInstance = new WaveDetail();
                            waveInstance.Distance = disArray;
                            waveInstance.Thickness = thickArray;
                            waveInstance.FinalThickness = thicknessValue;
                            waveInstance.FindThicknessIndex = thickIndex;
                            waveInstance.AvgThickness = avgAry;
                            waveInstance.ZoneLeft = diffZoneLeft;
                            waveInstance.ZoneRight = diffZoneRight;
                            result.Add(count.ToString(), waveInstance);
                            count++;
                        }

                        tempList.RemoveAt(index);
                        tempThickList.RemoveAt(index);

                    }
                    else
                    {
                        index = -1;
                    }

                }
                endtime = DateTime.Now;
                timediff = (endtime - starttime).TotalSeconds;
                //if (finalList.Count >= 48)
                //{
                //    break;
                //}
            }
            return result;
        }




        /// <summary>
        /// 计算膜厚算法使用脉冲
        /// </summary>
        /// <param name="detectionType">检测类型</param>
        /// <param name="dis">距离数组</param>
        /// <param name="thick">膜厚数组</param>
        /// <returns></returns>
        private async Task<Dictionary<string, WaveDetail>>/*Task<List<int>>*/ CalculateThicknessAlgorithmUsePulse(string detectionType, List<double> disList, List<double> thickList)
        {
            double temp = 0;//临时变量
            int findValidValueCount = 0;
            int idx = 0;
            //List<double> tempList = new List<double>();
            //List<double> tempThickList = new List<double>();
            List<SourceData> srcList = new List<SourceData>();
            List<int> pulsePosList = new List<int>();
            List<double> finalList = new List<double>();
            Dictionary<string, WaveDetail> result = new Dictionary<string, WaveDetail>();
            for (int i = 0; i < 130; i++)
            {
                disList.Insert(0, -2147.483648);
                disList.Add(-2147.483648);
                thickList.Add(-2147.483648);
                thickList.Insert(0, -2147.483648);
            }
            foreach (var item in disList)
            {
                if (item == -2147.483648)
                {
                    findValidValueCount++;
                    if (findValidValueCount >= 120)/*35*///120
                    {
                        if (item != temp)
                        {
                            //tempList.Add(item);
                            //tempThickList.Add(thickList[idx]);
                            srcList.Add(new SourceData() { PulseCount = idx + 1, Distance = item, Thickness = thickList[idx] });
                            temp = item;
                            findValidValueCount = 0;
                        }
                    }
                }
                else
                {
                    if (item != temp && item != -2147.483648)
                    {
                        //tempList.Add(item);
                        //tempThickList.Add(thickList[idx]);
                        srcList.Add(new SourceData() { PulseCount = idx + 1, Distance = item, Thickness = thickList[idx] });
                        temp = item;
                        findValidValueCount = 0;
                    }
                }
                idx++;
            }

            int index = srcList.FindIndex(f => f.Distance == -2147.483648);
            int endIndex = 0;
            DateTime starttime = DateTime.Now;
            DateTime endtime = DateTime.Now;
            double timediff = 0;
            int count = 1;
            while (index != -1)
            {
                index = srcList.FindIndex(f => f.Distance == -2147.483648);/*tempList.IndexOf(-2147.483648);*/

                if (index != -1)//找到起始位置
                {
                    endIndex = srcList.FindIndex(index + 1, f => f.Distance == -2147.483648);/*tempList.IndexOf(-2147.483648, index + 1);*/
                    if (endIndex != -1)//找到结束位置
                    {
                        double totalValue = 0;
                        double thicknessValue = 0;
                        //double[] disArray =  tempList.GetRange(index + 1, endIndex - index - 1).ToArray();//有效距离数组
                        //double[] thickArray = tempThickList.GetRange(index + 1, endIndex - index - 1).ToArray();
                        List<SourceData> dstList = srcList.GetRange(index + 1, endIndex - index - 1);

                        List<double> disArrayList = new List<double>();
                        List<double> thickArrayList = new List<double>();
                        List<int> pulseArrayList = new List<int>();

                        foreach (var item in dstList)
                        {
                            disArrayList.Add(item.Distance);
                            thickArrayList.Add(item.Thickness);
                            pulseArrayList.Add(item.PulseCount);
                        }

                        double[] disArray = disArrayList.ToArray();
                        double[] thickArray = thickArrayList.ToArray();
                        int[] pulseArray = pulseArrayList.ToArray();

                        double[] avgAry = new double[50];
                        avgAry.Initialize();
                        int thickIndex = 0;
                        if (detectionType.Contains("FCT"))
                        {
                            thickIndex = disArray.ToList().FindIndex(f => f == disArray.Max());//找到膜厚下标
                        }
                        else
                        {
                            thickIndex = disArray.ToList().FindIndex(f => f == disArray.Min());//找到膜厚下标
                        }
                        double diffZoneLeft = 0;
                        double diffZoneRight = 0;
                        try
                        {
                            if (thickIndex != -1)
                            {
                                diffZoneLeft = disArray[0] - disArray[thickIndex];
                                diffZoneRight = disArray[disArray.Length - 1] - disArray[thickIndex];
                            }
                            else
                            {
                                diffZoneLeft = 0;
                                diffZoneRight = 0;
                            }
                        }
                        catch
                        {
                            diffZoneLeft = 0;
                            diffZoneRight = 0;
                        }

                        bool resLeft = Judge(Math.Abs(diffZoneLeft));
                        bool resRight = Judge(Math.Abs(diffZoneRight));
                        bool res = true;
                        if (count == 1 || count == 2)
                        {
                            if (resLeft && resRight)
                            {
                                res = true;
                            }
                            else
                            {
                                res = false;
                            }
                        }
                        if (res)
                        {
                            int currentPulse = 0;
                            int lastPulse = 0;
                            int diffPulse = 0;
                            thicknessValue = CalculateAvgThicknessValue(thickIndex, thickArray, disArray, totalValue, avgAry);
                            finalList.Add(thicknessValue);
                            WaveDetail waveInstance = new WaveDetail();
                            waveInstance.Distance = disArray;
                            waveInstance.Thickness = thickArray;
                            waveInstance.FinalThickness = thicknessValue;
                            waveInstance.FindThicknessIndex = thickIndex;
                            waveInstance.AvgThickness = avgAry;
                            waveInstance.ZoneLeft = diffZoneLeft;
                            waveInstance.ZoneRight = diffZoneRight;
                            result.Add(count.ToString(), waveInstance);
                            count++;

                            #region 
                            //if (pulsePosList.Any())
                            //{
                            //    currentPulse = pulseArray[thickIndex];
                            //    lastPulse = pulsePosList.Last();
                            //    diffPulse = currentPulse - lastPulse;
                            //    if (diffPulse >= 600 && diffPulse <= 780)
                            //    {
                            //        pulsePosList.Add(pulseArray[thickIndex]);
                            //        //for (int i = 0; i < 25; i++)
                            //        //{
                            //        //    if (thickIndex + i < thickArray.Length - 1 && thickIndex - i < thickArray.Length - 1 /*&& thickIndex != 0*/ && thickIndex - i >= 0)
                            //        //    {
                            //        //        double value = thickArray[thickIndex - i];
                            //        //        if (value != -2147.483648)
                            //        //        {
                            //        //            totalValue += value;
                            //        //            avgAry[i] = value;
                            //        //            if (thickArray[thickIndex + i] != -2147.483648)
                            //        //            {
                            //        //                double valueSum = thickArray[thickIndex + i];
                            //        //                totalValue += valueSum;
                            //        //                avgAry[24 + i] = valueSum;
                            //        //            }
                            //        //        }
                            //        //        else if (thickArray[thickIndex + i] != -2147.483648)
                            //        //        {
                            //        //            double valueSum1 = thickArray[thickIndex + i];
                            //        //            totalValue += valueSum1;
                            //        //            avgAry[24 + i] = valueSum1;
                            //        //        }
                            //        //    }
                            //        //}
                            //        //thicknessValue = totalValue / avgAry.Where(f => f != 0).ToArray().Length;//均值计算
                            //        thicknessValue = CalculateAvgThicknessValue(thickIndex, thickArray, disArray, totalValue, avgAry);
                            //        finalList.Add(thicknessValue);
                            //        WaveDetail waveInstance = new WaveDetail();
                            //        waveInstance.Distance = disArray;
                            //        waveInstance.Thickness = thickArray;
                            //        waveInstance.FinalThickness = thicknessValue;
                            //        waveInstance.FindThicknessIndex = thickIndex;
                            //        waveInstance.AvgThickness = avgAry;
                            //        waveInstance.ZoneLeft = diffZoneLeft;
                            //        waveInstance.ZoneRight = diffZoneRight;
                            //        result.Add(count.ToString(), waveInstance);
                            //        count++;
                            //    }
                            //    else if (diffPulse > 780)
                            //    {
                            //        int findIdx = pulsePosList.Last() + 1000/*730*/;
                            //        pulsePosList.Add(findIdx);
                            //        int idxpulse = pulseArrayList.FindIndex(p => (p >= findIdx - 200 && p <= findIdx + 200));
                            //        if (idxpulse != -1)
                            //        {
                            //            thicknessValue = CalculateAvgThicknessValue(thickIndex, thickArray, disArray, totalValue, avgAry);
                            //            finalList.Add(thicknessValue);
                            //            WaveDetail waveInstance = new WaveDetail();
                            //            waveInstance.Distance = disArray;
                            //            waveInstance.Thickness = thickArray;
                            //            waveInstance.FinalThickness = thicknessValue;
                            //            waveInstance.FindThicknessIndex = thickIndex;
                            //            waveInstance.AvgThickness = avgAry;
                            //            waveInstance.ZoneLeft = diffZoneLeft;
                            //            waveInstance.ZoneRight = diffZoneRight;
                            //            result.Add(count.ToString(), waveInstance);
                            //            count++;
                            //        }
                            //        else
                            //        {
                            //            thicknessValue = 0;
                            //            finalList.Add(thicknessValue);
                            //            WaveDetail waveInstance = new WaveDetail();
                            //            waveInstance.Distance = new double[] { };
                            //            waveInstance.Thickness = new double[] { };
                            //            waveInstance.FinalThickness = thicknessValue;
                            //            waveInstance.FindThicknessIndex = 0;
                            //            waveInstance.AvgThickness = new double[] { };
                            //            waveInstance.ZoneLeft = 0;
                            //            waveInstance.ZoneRight = 0;
                            //            result.Add(count.ToString(), waveInstance);
                            //            count++;
                            //        }
                            //    }
                            //}
                            //else
                            //{
                            //    pulsePosList.Add(pulseArray[thickIndex]);
                            //    //for (int i = 0; i < 25; i++)
                            //    //{
                            //    //    if (thickIndex + i < thickArray.Length - 1 && thickIndex - i < thickArray.Length - 1 /*&& thickIndex != 0*/ && thickIndex - i >= 0)
                            //    //    {
                            //    //        double value = thickArray[thickIndex - i];
                            //    //        if (value != -2147.483648)
                            //    //        {
                            //    //            totalValue += value;
                            //    //            avgAry[i] = value;
                            //    //            if (thickArray[thickIndex + i] != -2147.483648)
                            //    //            {
                            //    //                double valueSum = thickArray[thickIndex + i];
                            //    //                totalValue += valueSum;
                            //    //                avgAry[24 + i] = valueSum;
                            //    //            }
                            //    //        }
                            //    //        else if (thickArray[thickIndex + i] != -2147.483648)
                            //    //        {
                            //    //            double valueSum1 = thickArray[thickIndex + i];
                            //    //            totalValue += valueSum1;
                            //    //            avgAry[24 + i] = valueSum1;
                            //    //        }
                            //    //    }
                            //    //}
                            //    //thicknessValue = totalValue / avgAry.Where(f => f != 0).ToArray().Length;//均值计算
                            //    thicknessValue = CalculateAvgThicknessValue(thickIndex, thickArray, disArray, totalValue, avgAry);
                            //    finalList.Add(thicknessValue);
                            //    WaveDetail waveInstance = new WaveDetail();
                            //    waveInstance.Distance = disArray;
                            //    waveInstance.Thickness = thickArray;
                            //    waveInstance.FinalThickness = thicknessValue;
                            //    waveInstance.FindThicknessIndex = thickIndex;
                            //    waveInstance.AvgThickness = avgAry;
                            //    waveInstance.ZoneLeft = diffZoneLeft;
                            //    waveInstance.ZoneRight = diffZoneRight;
                            //    result.Add(count.ToString(), waveInstance);
                            //    count++;
                            //}

                            //count++;
                            #endregion
                        }




                        #region
                        //if (disArray.Length > 40/*20*/ && res/*resLeft && resRight*/)
                        //{
                        //    for (int i = 0; i < 25; i++)
                        //    {
                        //        if (thickIndex + i < thickArray.Length - 1 && thickIndex - i < thickArray.Length - 1 /*&& thickIndex != 0*/ && thickIndex - i >= 0)
                        //        {
                        //            double value = thickArray[thickIndex - i];
                        //            if (value != -2147.483648)
                        //            {
                        //                totalValue += value;
                        //                avgAry[i] = value;
                        //                if (thickArray[thickIndex + i] != -2147.483648)
                        //                {
                        //                    double valueSum = thickArray[thickIndex + i];
                        //                    totalValue += valueSum;
                        //                    avgAry[24 + i] = valueSum;
                        //                }
                        //            }
                        //            else if (thickArray[thickIndex + i] != -2147.483648)
                        //            {
                        //                double valueSum1 = thickArray[thickIndex + i];
                        //                totalValue += valueSum1;
                        //                avgAry[24 + i] = valueSum1;
                        //            }
                        //        }
                        //    }
                        //    thicknessValue = totalValue / avgAry.Where(f => f != 0).ToArray().Length;//均值计算
                        //    finalList.Add(thicknessValue);
                        //    WaveDetail waveInstance = new WaveDetail();
                        //    waveInstance.Distance = disArray;
                        //    waveInstance.Thickness = thickArray;
                        //    waveInstance.FinalThickness = thicknessValue;
                        //    waveInstance.FindThicknessIndex = thickIndex;
                        //    waveInstance.AvgThickness = avgAry;
                        //    waveInstance.ZoneLeft = diffZoneLeft;
                        //    waveInstance.ZoneRight = diffZoneRight;
                        //    result.Add(count.ToString(), waveInstance);
                        //    count++;
                        //}

                        //tempList.RemoveAt(index);
                        //tempThickList.RemoveAt(index);
                        #endregion
                        srcList.RemoveAt(index);

                    }
                    else
                    {
                        index = -1;
                    }

                }
                endtime = DateTime.Now;
                timediff = (endtime - starttime).TotalSeconds;
                //if (finalList.Count >= 48)
                //{
                //    break;
                //}
            }
            return result;
            //return pulsePosList;
        }


        private double CalculateAvgThicknessValue(int thickIndex, double[] thickArray, double[] disArray, double totalValue, double[] avgAry)
        {
            for (int i = 0; i < 25; i++)
            {
                if (thickIndex + i < thickArray.Length - 1 && thickIndex - i < thickArray.Length - 1 /*&& thickIndex != 0*/ && thickIndex - i >= 0)
                {
                    double value = thickArray[thickIndex - i];
                    if (value != -2147.483648)
                    {
                        totalValue += value;
                        avgAry[i] = value;
                        if (thickArray[thickIndex + i] != -2147.483648)
                        {
                            double valueSum = thickArray[thickIndex + i];
                            totalValue += valueSum;
                            avgAry[24 + i] = valueSum;
                        }
                    }
                    else if (thickArray[thickIndex + i] != -2147.483648)
                    {
                        double valueSum1 = thickArray[thickIndex + i];
                        totalValue += valueSum1;
                        avgAry[24 + i] = valueSum1;
                    }
                }
            }
            double thicknessValue = totalValue / avgAry.Where(f => f != 0).ToArray().Length;//均值计算
            return thicknessValue;
        }



        private void btnCheck_Click(object sender, EventArgs e)
        {
            ShowWave(Convert.ToInt32(txtIndex.Text));
        }

        private void ShowWave(int index)
        {
            lblMin.Text = "";
            lblMax.Text = "";
            try
            {
                lblType.Text = cmbItem.Text;
                WaveDetail wave = FilterWave(cmbItem.Text, index);
                lblMax.Text = wave.AvgThickness.Max().ToString();
                lblMin.Text = wave.AvgThickness.Min().ToString();
                lblLeft.Text = wave.ZoneLeft.ToString();
                lblRight.Text = wave.ZoneRight.ToString();
                lblValue.Text = wave.FinalThickness.ToString();
                chartDst.Series["Series1"].Points.Clear();
                chartDst.Series["Series2"].Points.Clear();
                string content = "";
                for (int i = 0; i < wave.Distance.Length; i++)
                {
                    chartDst.Series["Series1"].Points.AddXY(i + 1, wave.Distance[i]);
                    //chartDst.Series["Series2"].Points.AddXY(i + 1, wave.Thickness[i]);
                    if (wave.Thickness[i] > 0)
                    {
                        chartDst.Series["Series2"].Points.AddXY(i + 1, wave.Thickness[i]);
                    }
                    content += wave.Thickness[i].ToString() + "\r\n";
                }
                txtDst.Text = content;
            }
            catch (Exception ex)
            {
                index = 1;
                txtDst.Text = "";
                chartDst.Series["Series1"].Points.Clear();
                chartDst.Series["Series2"].Points.Clear();
                MessageBox.Show(ex.Message);
            }
        }

        public WaveDetail FilterWave(string item, int index)
        {
            try
            {
                switch (item)
                {
                    case "FrontA":
                        return frontThicknessADic[index.ToString()];
                    case "FrontB":
                        return frontThicknessBDic[index.ToString()];
                    case "BackA":
                        return backThicknessADic[index.ToString()];
                    case "BackB":
                        return backThicknessBDic[index.ToString()];
                    default:
                        return null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

        System.Windows.Forms.DataVisualization.Charting.ToolTipEventArgs toolTipEventArgs;
        private void chartDst_GetToolTipText(object sender, System.Windows.Forms.DataVisualization.Charting.ToolTipEventArgs e)
        {
            toolTipEventArgs = e;

            if (e.HitTestResult.ChartElementType == System.Windows.Forms.DataVisualization.Charting.ChartElementType.DataPoint)
            {
                int i = e.HitTestResult.PointIndex;
                System.Windows.Forms.DataVisualization.Charting.DataPoint dp = e.HitTestResult.Series.Points[i];
                e.Text = string.Format("A:{0},T:{1}", dp.XValue.ToString(), dp.YValues[0]);
            }
        }

        int index = 1;
        private void btnNext_Click(object sender, EventArgs e)
        {
            /*int index = Convert.ToInt32(txtIndex.Text)*/
            try
            {
                ShowWave(index);
                if (index < 49)
                {
                    txtIndex.Text = index.ToString();
                    ++index;

                }
                else
                {
                    txtIndex.Text = "1";
                    index = 1;
                }
            }
            catch
            {
                index = 1;
            }
        }
    }

    public class WaveDetail
    {
        /// <summary>
        /// 距离数组
        /// </summary>
        public double[] Distance { get; set; }
        /// <summary>
        /// 膜厚数组
        /// </summary>
        public double[] Thickness { get; set; }
        /// <summary>
        /// 最终厚度
        /// </summary>
        public double FinalThickness { get; set; }
        /// <summary>
        /// 膜厚下标
        /// </summary>
        public int FindThicknessIndex { get; set; }
        /// <summary>
        /// 取均值的膜厚数组
        /// </summary>
        public double[] AvgThickness { get; set; }
        public double ZoneLeft { get; set; }
        public double ZoneRight { get; set; }
    }

    public class SourceData
    {
        /// <summary>
        /// 脉冲
        /// </summary>
        public int PulseCount { get; set; }
        /// <summary>
        /// 距离
        /// </summary>
        public double Distance { get; set; }
        /// <summary>
        /// 膜厚
        /// </summary>
        public double Thickness { get; set; }
    }
}
